import 'package:flutter/material.dart';
import '../../models/follow_category_model.dart';
import '../../utils/cached_image_widget.dart';

class FollowCategoryManagementPage extends StatefulWidget {
  const FollowCategoryManagementPage({super.key});

  @override
  State<FollowCategoryManagementPage> createState() =>
      _FollowCategoryManagementPageState();
}

class _FollowCategoryManagementPageState
    extends State<FollowCategoryManagementPage> {
  // 模拟关注分类数据
  List<FollowCategory> _followCategories = [
    FollowCategory(
        id: '1',
        name: '家人',
        color: '#FF6B6B',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '2',
        name: '同事',
        color: '#4ECDC4',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '3',
        name: '高人',
        color: '#45B7D1',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '4',
        name: '朋友',
        color: '#96CEB4',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '5',
        name: '客户',
        color: '#FFEAA7',
        isDefault: true,
        createdAt: DateTime.now()),
    FollowCategory(
        id: '6',
        name: '合作伙伴',
        color: '#DDA0DD',
        isDefault: false,
        createdAt: DateTime.now()),
  ];

  // 模拟已关注用户数据
  final Map<String, List<FollowedUser>> _followedUsersByCategory = {
    '1': [
      FollowedUser(
          userId: '101',
          username: '妈妈',
          avatar: '',
          categoryId: '1',
          followedAt: DateTime.now().subtract(const Duration(days: 30))),
      FollowedUser(
          userId: '102',
          username: '爸爸',
          avatar: '',
          categoryId: '1',
          followedAt: DateTime.now().subtract(const Duration(days: 25))),
    ],
    '2': [
      FollowedUser(
          userId: '201',
          username: '张经理',
          avatar: '',
          categoryId: '2',
          followedAt: DateTime.now().subtract(const Duration(days: 20))),
      FollowedUser(
          userId: '202',
          username: '李同事',
          avatar: '',
          categoryId: '2',
          followedAt: DateTime.now().subtract(const Duration(days: 15))),
    ],
    '3': [
      FollowedUser(
          userId: '301',
          username: '王专家',
          avatar: '',
          categoryId: '3',
          followedAt: DateTime.now().subtract(const Duration(days: 10))),
    ],
    '4': [
      FollowedUser(
          userId: '401',
          username: '小明',
          avatar: '',
          categoryId: '4',
          followedAt: DateTime.now().subtract(const Duration(days: 5))),
      FollowedUser(
          userId: '402',
          username: '小红',
          avatar: '',
          categoryId: '4',
          followedAt: DateTime.now().subtract(const Duration(days: 3))),
    ],
    '5': [
      FollowedUser(
          userId: '501',
          username: '客户A',
          avatar: '',
          categoryId: '5',
          followedAt: DateTime.now().subtract(const Duration(days: 1))),
    ],
    '6': [
      FollowedUser(
          userId: '601',
          username: '合作伙伴B',
          avatar: '',
          categoryId: '6',
          followedAt: DateTime.now()),
    ],
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('关注标签管理'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showAddCategoryDialog(),
          ),
        ],
      ),
      body: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _followCategories.length,
        itemBuilder: (context, index) {
          final category = _followCategories[index];
          final userCount = _followedUsersByCategory[category.id]?.length ?? 0;

          return Card(
            margin: const EdgeInsets.only(bottom: 12),
            child: ExpansionTile(
              leading: Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  color:
                      Color(int.parse(category.color.replaceAll('#', '0xFF'))),
                  shape: BoxShape.circle,
                ),
              ),
              title: Row(
                children: [
                  Text(
                    category.name,
                    style: const TextStyle(fontWeight: FontWeight.w500),
                  ),
                  if (category.isDefault)
                    Container(
                      margin: const EdgeInsets.only(left: 8),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.grey.withOpacity(0.2),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Text(
                        '默认',
                        style: TextStyle(fontSize: 10, color: Colors.grey),
                      ),
                    ),
                ],
              ),
              subtitle: Text('$userCount 个关注用户'),
              trailing: category.isDefault
                  ? null
                  : Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.edit, size: 20),
                          onPressed: () => _showEditCategoryDialog(category),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete,
                              size: 20, color: Colors.red),
                          onPressed: () => _showDeleteCategoryDialog(category),
                        ),
                      ],
                    ),
              children: [
                if (_followedUsersByCategory[category.id] != null)
                  ..._followedUsersByCategory[category.id]!
                      .map((user) => _buildUserItem(user, category)),
                if (_followedUsersByCategory[category.id]?.isEmpty ?? true)
                  const Padding(
                    padding: EdgeInsets.all(16),
                    child: Text(
                      '暂无关注用户',
                      style: TextStyle(color: Colors.grey),
                      textAlign: TextAlign.center,
                    ),
                  ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildUserItem(FollowedUser user, FollowCategory category) {
    return ListTile(
      leading: CachedAvatarWidget(
        avatarUrl: user.avatar,
        size: 40,
      ),
      title: Text(user.username),
      subtitle: Text('关注时间：${_formatDate(user.followedAt)}'),
      trailing: PopupMenuButton<String>(
        onSelected: (value) {
          if (value == 'move') {
            _showMoveUserDialog(user, category);
          } else if (value == 'unfollow') {
            _showUnfollowDialog(user);
          }
        },
        itemBuilder: (context) => [
          const PopupMenuItem(
            value: 'move',
            child: Row(
              children: [
                Icon(Icons.move_to_inbox),
                SizedBox(width: 8),
                Text('移动到其他标签'),
              ],
            ),
          ),
          const PopupMenuItem(
            value: 'unfollow',
            child: Row(
              children: [
                Icon(Icons.person_remove, color: Colors.red),
                SizedBox(width: 8),
                Text('取消关注', style: TextStyle(color: Colors.red)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _showAddCategoryDialog() {
    final TextEditingController nameController = TextEditingController();
    String selectedColor = '#FF6B6B';

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('添加自定义标签'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '标签名称',
                  hintText: '请输入标签名称',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),
              const Text('选择颜色：'),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                children: [
                  '#FF6B6B',
                  '#4ECDC4',
                  '#45B7D1',
                  '#96CEB4',
                  '#FFEAA7',
                  '#DDA0DD',
                  '#FFB6C1',
                  '#98FB98',
                  '#87CEEB',
                  '#DDA0DD',
                  '#F0E68C',
                  '#FFA07A'
                ]
                    .map((color) => GestureDetector(
                          onTap: () => setState(() => selectedColor = color),
                          child: Container(
                            width: 30,
                            height: 30,
                            decoration: BoxDecoration(
                              color: Color(
                                  int.parse(color.replaceAll('#', '0xFF'))),
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: selectedColor == color
                                    ? Colors.black
                                    : Colors.transparent,
                                width: 2,
                              ),
                            ),
                          ),
                        ))
                    .toList(),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                if (nameController.text.trim().isNotEmpty) {
                  final newCategory = FollowCategory(
                    id: DateTime.now().millisecondsSinceEpoch.toString(),
                    name: nameController.text.trim(),
                    color: selectedColor,
                    isDefault: false,
                    createdAt: DateTime.now(),
                  );
                  setState(() {
                    _followCategories.add(newCategory);
                    _followedUsersByCategory[newCategory.id] = [];
                  });
                  Navigator.pop(context);
                  _showSuccessMessage('标签创建成功');
                }
              },
              child: const Text('创建'),
            ),
          ],
        ),
      ),
    );
  }

  void _showEditCategoryDialog(FollowCategory category) {
    final TextEditingController nameController =
        TextEditingController(text: category.name);
    String selectedColor = category.color;

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('编辑标签'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '标签名称',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),
              const Text('选择颜色：'),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                children: [
                  '#FF6B6B',
                  '#4ECDC4',
                  '#45B7D1',
                  '#96CEB4',
                  '#FFEAA7',
                  '#DDA0DD',
                  '#FFB6C1',
                  '#98FB98',
                  '#87CEEB',
                  '#DDA0DD',
                  '#F0E68C',
                  '#FFA07A'
                ]
                    .map((color) => GestureDetector(
                          onTap: () => setState(() => selectedColor = color),
                          child: Container(
                            width: 30,
                            height: 30,
                            decoration: BoxDecoration(
                              color: Color(
                                  int.parse(color.replaceAll('#', '0xFF'))),
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: selectedColor == color
                                    ? Colors.black
                                    : Colors.transparent,
                                width: 2,
                              ),
                            ),
                          ),
                        ))
                    .toList(),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                if (nameController.text.trim().isNotEmpty) {
                  final updatedCategory = FollowCategory(
                    id: category.id,
                    name: nameController.text.trim(),
                    color: selectedColor,
                    isDefault: category.isDefault,
                    createdAt: category.createdAt,
                  );
                  setState(() {
                    final index = _followCategories
                        .indexWhere((c) => c.id == category.id);
                    if (index != -1) {
                      _followCategories[index] = updatedCategory;
                    }
                  });
                  Navigator.pop(context);
                  _showSuccessMessage('标签更新成功');
                }
              },
              child: const Text('保存'),
            ),
          ],
        ),
      ),
    );
  }

  void _showDeleteCategoryDialog(FollowCategory category) {
    final userCount = _followedUsersByCategory[category.id]?.length ?? 0;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除标签'),
        content: Text('确定要删除标签"${category.name}"吗？\n该标签下有 $userCount 个关注用户。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _followCategories.removeWhere((c) => c.id == category.id);
                _followedUsersByCategory.remove(category.id);
              });
              Navigator.pop(context);
              _showSuccessMessage('标签删除成功');
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  void _showMoveUserDialog(FollowedUser user, FollowCategory currentCategory) {
    final availableCategories =
        _followCategories.where((c) => c.id != currentCategory.id).toList();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('移动用户'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('将"${user.username}"移动到：'),
            const SizedBox(height: 16),
            ...availableCategories.map((category) => ListTile(
                  leading: Container(
                    width: 20,
                    height: 20,
                    decoration: BoxDecoration(
                      color: Color(
                          int.parse(category.color.replaceAll('#', '0xFF'))),
                      shape: BoxShape.circle,
                    ),
                  ),
                  title: Text(category.name),
                  onTap: () {
                    setState(() {
                      // 从当前分类移除
                      _followedUsersByCategory[currentCategory.id]
                          ?.removeWhere((u) => u.userId == user.userId);

                      // 添加到新分类
                      final updatedUser = FollowedUser(
                        userId: user.userId,
                        username: user.username,
                        avatar: user.avatar,
                        categoryId: category.id,
                        followedAt: user.followedAt,
                      );
                      _followedUsersByCategory[category.id]?.add(updatedUser);
                    });
                    Navigator.pop(context);
                    _showSuccessMessage('用户移动成功');
                  },
                )),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _showUnfollowDialog(FollowedUser user) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('取消关注'),
        content: Text('确定要取消关注"${user.username}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _followedUsersByCategory[user.categoryId]
                    ?.removeWhere((u) => u.userId == user.userId);
              });
              Navigator.pop(context);
              _showSuccessMessage('已取消关注');
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('确定', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  void _showSuccessMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }
}
